package com.jyw.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.Coupon;
import com.jyw.thirdparty.Divider;
import com.jyw.thirdparty.DividerItemDecoration;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/7
 */

public class CouponActivity extends BaseActivity implements View.OnClickListener {
    private TextView tvHow;
    private RecyclerView recycler;
    private CouponAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coupon);
        findViewById(R.id.iv_back).setOnClickListener(this);
        tvHow = (TextView) findViewById(R.id.tv_how);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        tvHow.setOnClickListener(this);

        recycler.setLayoutManager(new LinearLayoutManager(CouponActivity.this));
        DividerItemDecoration deco = new DividerItemDecoration();
        deco.setDividerLookup(new DividerItemDecoration.DividerLookup() {
            @Override
            public Divider getVerticalDivider(int position) {
                return null;
            }

            @Override
            public Divider getHorizontalDivider(int position) {
                return new Divider.Builder().color(Color.TRANSPARENT).size(24).build();
            }
        });
        recycler.addItemDecoration(deco);
        recycler.setAdapter(adapter = new CouponAdapter());

        loadData();
    }

    private void loadData() {
        Request request = new Request.Builder().
                url(Server.GET_COUPON + "?phone_data=" + getPrefs().getString("phone", "")).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(CouponActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    org.json.JSONArray arr = new org.json.JSONArray(response.body().string());
                    final List<Coupon> coupons = new ArrayList<>();
                    Gson gson = new Gson();
                    for (int i = 0; i < arr.length(); i++) {
                        coupons.add(gson.fromJson(arr.get(i).toString(), Coupon.class));
                    }
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);
                            Collections.reverse(coupons);
                            adapter.swapData(coupons);
                        }
                    }.execute();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class CouponAdapter extends RecyclerView.Adapter<CouponAdapter.CouponHolder> {
        private List<Coupon> data = new ArrayList<>();

        void swapData(List<Coupon> data0) {
            this.data = data0;
            notifyDataSetChanged();
        }

        @Override
        public CouponHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new CouponHolder(LayoutInflater.from(CouponActivity.this).inflate(R.layout.item_coupon, null));
        }

        @Override
        public void onBindViewHolder(CouponHolder holder, final int position) {
            holder.tvMoney.setText(data.get(position).getMoney());
            holder.tvBetween.setText("有效期：" + data.get(position).getCreate_time() + "至" + data.get(position).getEnd_time());
            if (TextUtils.isEmpty(getIntent().getStringExtra("order_id"))) {
                holder.v.setClickable(false);
            } else {
                holder.v.setClickable(true);
                holder.v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(CouponActivity.this, OrderPayActivity.class);
                        intent.putExtra("order_id", getIntent().getStringExtra("order_id"));
                        intent.putExtra("coupon_money", data.get(position).getMoney());
                        intent.putExtra("coupon_id", data.get(position).getId());
                        startActivity(intent);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }

        class CouponHolder extends RecyclerView.ViewHolder {
            View v;
            TextView tvMoney, tvBetween;

            CouponHolder(View itemView) {
                super(itemView);
                v = itemView;
                tvMoney = (TextView) itemView.findViewById(R.id.tv_money);
                tvBetween = (TextView) itemView.findViewById(R.id.tv_between);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_how:
                startActivity(new Intent(CouponActivity.this, CouponHowActivity.class));
                break;
        }
    }
}
